//
//  DownloadManager.m
//  仿SDWebImage
//
//  Created by WangBiao on 16/9/18.
//  Copyright © 2016年 lsrain. All rights reserved.
//

#import "DownloadManager.h"
#import "DownloadOperation.h"
#import "NSString+path.h"

@interface DownloadManager()

//需求：实现缓存控制，重复下载取消、内存警告处理
///全局队列
@property (nonatomic, strong) NSOperationQueue *queue;

///操作缓存池
@property (nonatomic, strong) NSMutableDictionary *OPCache;

///图片缓存池
@property (nonatomic, strong) NSMutableDictionary *imgsCache;

@end

@implementation DownloadManager

//需求：持有自定义Operation的block-finishBlock

//需求：修改写入沙盒，没有获得缓存图片
///finishBlock回调的时候回调UIImageView分类的block
- (void)downloadImgWithURLString:(NSString *)URLString andFinishBlock:(void(^)(UIImage *img))finish{
    
    //判断是否在缓存中已经存在
    if ([self checkCacheWithURLString:URLString]) {
        //如果在缓存中已经存在，就返回内存中的图片，不再进行下载
        if (finish) {
            finish([self.imgsCache objectForKey:URLString]);
        }
    }
    
    //如果相同的操作，就返回，不再下载
    if ([self.OPCache objectForKey:URLString]) {
        return;
    }
    
    //需要回调Download
   DownloadOperation *op = [DownloadOperation downloadImageWithURLString:URLString finishBlcok:^(UIImage *img) {
        //当图片下载完成回调时，回调UIImageView的分类
        finish(img);
       
       //下载完成移除操作
       [self.OPCache removeObjectForKey:URLString];
    }];
    
    //添加下载操作
    [self.OPCache setObject:op forKey:URLString];
    
    [self.queue addOperation:op];
}

//需求：实现判断图片是否已经在缓存中存在
- (BOOL)checkCacheWithURLString:(NSString *)URLString{
    if ([self.imgsCache objectForKey:URLString]) {
        NSLog(@"从内存加载....");
        return YES;
    }
    
    UIImage *img = [UIImage imageWithContentsOfFile:[URLString appendCache]];
    if(img){
        //在内存中存储一份
        [self.imgsCache setObject:img forKey:URLString];
        NSLog(@"从沙盒加载....");
        return YES;
    }
    
    return NO;
}

///取消重复操作
- (void)cancelOperationOfLastURL:(NSString *)lastURL{
    [[self.OPCache objectForKey:lastURL] cancel];
    [self.OPCache removeObjectForKey:lastURL];
}

+ (instancetype)sharedManager{
    
    static id instance;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc]init];
    });
    
    return instance;
}

//需求：处理内存警告
///实例化缓存池和队列
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.queue = [[NSOperationQueue alloc]init];
        self.OPCache = [[NSMutableDictionary alloc]init];
        self.imgsCache = [[NSMutableDictionary alloc]init];
        
        //使用通知注册内存警告
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearMemery) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
    }
    return self;
}

- (void)clearMemery{
    [self.OPCache removeAllObjects];
    [self.imgsCache removeAllObjects];
    [self.queue cancelAllOperations];
}

@end
